package web

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"strconv"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
)

// QueryTopic 查询题目
func QueryTopic(c *gin.Context) {
	DB := common.GetDB()
	subject := c.PostForm("subject")
	paperId := c.PostForm("paperId")
	pageSize, _ := strconv.Atoi(c.PostForm("pageSize"))
	pageIndex, _ := strconv.Atoi(c.PostForm("pageIndex"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageIndex <= 0 {
		pageIndex = 1
	}

	if PaperIdExits(DB, paperId) {
		topic := make([]model.Topic, 0)
		var total int
		if subject != "" {
			DB.Where("paper_id = ?", paperId).Where("subject LIKE ?", "%"+subject+"%").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&topic).Offset(-1).Limit(-1).Count(&total)
			response.Reponse(c, http.StatusOK, 200, gin.H{
				"data":     topic,
				"total":    total,
				"page":     pageIndex,
				"pageSize": pageSize,
			}, "获取成功")
			return
		} else {
			DB.Where("paper_id = ?", paperId).Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&topic).Offset(-1).Limit(-1).Count(&total)
			response.Reponse(c, http.StatusOK, 200, gin.H{
				"data":     topic,
				"total":    total,
				"page":     pageIndex,
				"pageSize": pageSize,
			}, "获取成功")
			return
		}
		return
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "传入的试卷Id不存在")
		return
	}
}

func PaperIdExits(db *gorm.DB, paperId string) bool {
	var testPaper model.TestPaper
	db.Where("paper_id = ?", paperId).First(&testPaper)
	if testPaper.ID != 0 {
		//fmt.Println("是否进入判断", testPaper)
		return true
	}
	return false
}
